using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Daemon.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DaemonAPI.Middleware
{
    public class WebApiResultMiddleware : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var objectResult = context.Result as dynamic;
            var properties = context.Result.GetType().GetProperties().Select(r => r.Name);
        
            if (properties.Contains("Value") && objectResult?.Value != null)
            {
                context.Result = new ObjectResult(objectResult?.Value);
                return;
            }
            context.Result = new ObjectResult(new { StatusCode = objectResult?.StatusCode, Items = objectResult?.Items, Msg = objectResult?.Msg });
        }
    }
}
